from .item import *
from .singal import *
from .log import get_logger

manager_logger=get_logger('ItemManager')

class ItemManager:

    

    @staticmethod
    def update(item:ItemBase,field,value):
        item.__class__.update(**{field:value}).where(item.__class__.id==item.get_id()).execute()
    
    @staticmethod
    def add_book_item(book_title,book_url,cover_url,chapter_count,state=ItemState.Collecting):
        book_item=BookItem(title=book_title,url=book_url,cover_url=cover_url,chapter_count=chapter_count,state=state)
        book_item.save()
        manager_logger.debug('Save book item successfually!')
        return book_item
    
    @staticmethod    
    def add_chapter_item(chapter_title,order,chapter_url,page_count,book_item,state=ItemState.Collecting):
        chapter_item=ChapterItem()
        chapter_item.book=book_item
        chapter_item.title=chapter_title
        chapter_item.page_count=page_count
        chapter_item.url=chapter_url
        chapter_item.order=order
        chapter_item.state=state
        chapter_item.save()
        manager_logger.debug('Save chapter item successfually!')
        return chapter_item
    
    @staticmethod
    def add_page_item(order,page_url,chapter_item):
        PageItem.create(order=order,url=page_url,chapter=chapter_item)
    
    @staticmethod
    def add_page_items(page_url_list,chapter_item):
        rows=[(order,page_url,chapter_item) for order,page_url in enumerate(page_url_list)]
        fields=[PageItem.order,PageItem.url,PageItem.chapter]
        PageItem.insert_many(rows,fields).execute()
        manager_logger.debug('Save page items successfually!')
    
    @staticmethod
    def update_item_state(item:ItemBase,state:ItemState):
        ItemManager.update(item,'state',state)


    
    @staticmethod
    def reset_download_state(book_item:BookItem):
        ItemManager.update_item_state(book_item,ItemState.Downloading)
        ChapterItem.update(state=ItemState.Downloading).where(ChapterItem.book==book_item).execute()
        for chapter_item in book_item.chapters:
            PageItem.update(state=ItemState.Downloading).where(PageItem.chapter==chapter_item).execute()